<template>
  <div class="register-container">
    <el-card class="register-card">
      <div class="register-title">用户注册</div>
      <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
        <el-form-item prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="User" @input="handleInput('username', $event)" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" @input="handleInput('password', $event)" />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" prefix-icon="Lock" @input="handleInput('confirmPassword', $event)" />
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="registerForm.email" type="email" placeholder="请输入邮箱" prefix-icon="Message" @input="handleInput('email', $event)" />
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="registerForm.code" placeholder="请输入验证码" prefix-icon="Message">
            <template #suffix>
              <el-button type="text" @click="getCode" :disabled="countDown > 0">{{ countDown > 0 ? `${countDown}秒后重新获取` : '获取验证码' }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="agreement">
          <el-checkbox v-model="registerForm.agreement" ref="agreementCheckbox">我已阅读并同意<a href="#" class="agreement-link">用户协议</a>和<a href="#" class="agreement-link">隐私政策</a></el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="register-btn" @click="handleRegister">注册</el-button>
        </el-form-item>
        <div class="login-link">
          已有账号? <el-link type="primary" :underline="false" @click="goToLogin">立即登录</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';

// 添加输入处理函数，确保输入值立即更新
const handleInput = (field, value) => {
  console.log(`更新${field}:`, value);
  registerForm[field] = value;
};

import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '../utils/request';

const router = useRouter();
const countDown = ref(0);

const registerForm = reactive({
      username: '',
      password: '',
      confirmPassword: '',
      email: '',
      code: '',
      agreement: false
    });

// 监听agreement字段变化
watch(() => registerForm.agreement, (newValue) => {
  console.log('用户协议同意状态:', newValue);
});

// 组件挂载后检查复选框状态
// 已在顶部导入onMounted
onMounted(() => {
  console.log('注册表单组件已挂载');
  // 确保复选框初始状态正确
  if (registerForm.agreement !== false) {
    registerForm.agreement = false;
  }
});

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: ['input', 'blur'] },
    { min: 3, max: 20, message: '用户名长度在3-20个字符之间', trigger: ['input', 'blur'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: ['input', 'blur'] },
    { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: ['input', 'blur'] }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: ['input', 'blur'] },
    { validator: (rule, value, callback) => {
      if (value !== registerForm.password) {
        callback(new Error('两次密码输入不一致'));
      } else {
        callback();
      }
    }, trigger: ['input', 'blur'] }
  ],
  email: [
      { required: true, message: '请输入邮箱', trigger: ['input', 'blur'] },
      { pattern: /^[0-9a-zA-Z_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱格式', trigger: ['input', 'blur'] }
    ],
  code: [
    { required: true, message: '请输入验证码', trigger: ['input', 'blur'] },
    { len: 6, message: '验证码长度为6位', trigger: ['input', 'blur'] }
  ],
  agreement: [
    { validator: (rule, value, callback) => {
      if (!value) {
        callback(new Error('请阅读并同意用户协议和隐私政策'));
      } else {
        callback();
      }
    }, trigger: 'change' }
  ]
};

const handleRegister = async () => {
  try {
    const username = registerForm.username;
    const password = registerForm.password;
    const email = registerForm.email;
    const code = registerForm.code;
    const response = await request.post('/user/register', { username, password, email, code });
    if (response.success) {
      ElMessage.success('注册成功，请登录');
      router.push('/login');
    } else {
      ElMessage.error(response.message || '注册失败');
    }
  } catch (error) {
    ElMessage.error('注册失败，请重试');
  }
};

const getCode = () => {
    console.log('获取验证码按钮被点击');
    console.log('当前registerForm完整数据:', registerForm);
    const email = registerForm.email;
    console.log('获取的邮箱值:', email);
    if (!email || !/^[0-9a-zA-Z_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)) {
      console.info("邮箱验证失败，当前输入的邮箱为：", email);
      ElMessage.warning('请输入正确的邮箱');
      return;
    }

    // 实际调用发送验证码接口
    request.post('/user/sendCode', { email }).then(res => {
      if (res.code === 200) {
        ElMessage.success('验证码发送成功，请注意查收');
        countDown.value = 60;
        const timer = setInterval(() => {
          countDown.value--;
          if (countDown.value <= 0) {
            clearInterval(timer);
          }
        }, 1000);
      } else {
        ElMessage.error(res.message || '验证码发送失败');
      }
    }).catch(error => {
      ElMessage.error('验证码发送失败，请重试');
    });
  };

const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.register-card {
  width: 400px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  overflow: hidden;
}

.register-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin: 20px 0;
  color: #303133;
}

.register-form {
  padding: 20px;
}

.register-btn {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.login-link {
  text-align: center;
  margin-top: 15px;
  color: #606266;
}

.agreement-link {
  color: #409eff;
}

/* 确保复选框可见且可交互 */
.el-checkbox {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.el-checkbox__inner {
  width: 16px;
  height: 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-sizing: border-box;
  position: relative;
  background-color: #fff;
  transition: border-color 0.2s;
}

.el-checkbox__inner:hover {
  border-color: #4096ff;
}

.el-checkbox__input.is-checked .el-checkbox__inner {
  border-color: #4096ff;
  background-color: #4096ff;
}

/* 原生输入框样式 */
.native-input-wrapper {
  display: flex;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 15px;
  height: 40px;
  box-sizing: border-box;
  transition: border-color 0.2s;
}

.native-input-wrapper:focus-within {
  border-color: #4096ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(64, 150, 255, 0.2);
}

.input-icon {
  margin-right: 10px;
  color: #c0c4cc;
  font-size: 16px;
}

.native-input {
  flex: 1;
  height: 100%;
  border: none;
  outline: none;
  font-size: 14px;
  color: #606266;
  background-color: transparent;
}

.native-input::placeholder {
  color: #c0c4cc;
}

.with-suffix {
  position: relative;
  padding-right: 100px;
}

.code-button {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  padding: 4px 15px;
  color: #4096ff;
  background-color: transparent;
  border: none;
  outline: none;
  cursor: pointer;
  font-size: 14px;
}

.code-button:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}
</style>